/**
 * 
 */
package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.jdy.haoduoaiteacher.MyTeacherApp;
import com.jdy.haoduoaiteacher.adapter.PainPointDiscussionAdapter;
import com.jdy.haoduoaiteacher.intface.CommentDelegate;
import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.model.LeUser;
import com.jdy.haoduoaiteacher.model.PainPointDiscussionItem;
import com.jdy.haoduoaiteacher.model.PainPointDiscussionItemWrapper;
import com.jdy.haoduoaiteacher.parse.JsonSerializer;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.ListViewForScrollView;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.HashMap;

//import com.jdy.haoduoaiteacher.R;

/**
 * @author zp 2016-11-29 下午1:46:01
 */
public class PainPointDiscussionActivity extends BaseActivity implements
    OnClickListener {

  private static final String TAG = PainPointDiscussionActivity.class
      .getSimpleName();

  @InjectView(id = R.id.discussion_content_lv)
  private ListViewForScrollView mDiscussionListView;

  @InjectView(id = R.id.edit_img, click = true)
  private ImageView mAddCommentImg;

  @InjectView(id = R.id.detail_content_tv)
  private TextView mPainDetailTv;

  @InjectView(id = R.id.join_btn, click = true)
  private Button mJoinBtn;

  @InjectView(id = R.id.participate_number_tv)
  private TextView mParticipateTv;

  @InjectView(id = R.id.pain_name_tv)
  private TextView mNameTv;

  @InjectView(id = R.id.pain_desc_tv)
  private TextView mDesTv;

  @InjectView(id = R.id.discussion_back_btn)
  private ImageButton mDisBackIb;

  @InjectView(id = R.id.painpoint_img)
  private ImageView mBackImg;

  private PainPointDiscussionAdapter mPpdAdapter;

  private DialogHolder dialogHolder;

  private int mPID = 0;

  private int mHabitId = -1;

  private ArrayList<Integer> mSelectedList;

  private boolean mSelected = false, lastSelect = false;

  private static class DialogHolder {
    public Dialog dialog;
    public EditText editText;
    @SuppressWarnings("unused")
    public ImageView img;
  }

  private ArrayList<PainPointDiscussionItem> mDiscussionItemList;

  private PainPointDiscussionItemWrapper mPPDIW;

  private View mFooterView;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.painpoint_discussion_layout);

    Intent intent = getIntent();

    final Bundle extraBundle = intent.getExtras();

    mSelectedList = extraBundle.getIntegerArrayList("selected_list");

    hideTitleView();
    setupDialog();
    this.mDisBackIb.setOnTouchListener(new OnTouchListener() {
      @SuppressLint("ClickableViewAccessibility")
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
          mDisBackIb.setColorFilter(0x99c7c7c7,
              android.graphics.PorterDuff.Mode.MULTIPLY);
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
          mDisBackIb.setColorFilter(null);
        }
        return false;
      }
    });

    this.mDisBackIb.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {

        if (lastSelect != mSelected) {
          Intent resultIntent = new Intent();
          setResult(RESULT_OK, resultIntent);
        }

        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
      }
    });

    String img = getIntent().getStringExtra("img");

    if (Tools.isNotEmpty(img)) {
      Picasso.with(this).load(img).into(mBackImg);
    }

    String name = getIntent().getStringExtra("name");

    mNameTv.setText(name);

    int number = getIntent().getIntExtra("number", 0);

    mHabitId = intent.getIntExtra("habit_id", -1);

    mSelected = intent.getBooleanExtra("selected", false);

    lastSelect = mSelected;

    if (mSelected) {
      mJoinBtn.setBackgroundColor(Color.argb(255, 108, 230, 130));
      mJoinBtn.setText("已加入好习惯培养");
    } else {
      mJoinBtn.setBackgroundColor(Color.argb(255, 106, 197, 253));
      mJoinBtn.setText("加入好习惯培养");
    }

    mParticipateTv.setText("已有" + number + "人参加");

    String detail = getIntent().getStringExtra("description");

    if (detail != null)
      mPainDetailTv.setText(detail);

    mPainDetailTv.setText(getIntent().getStringExtra("desc"));

    String shortDesc = getIntent().getStringExtra("desc_short");

    if (Tools.isNotEmpty(shortDesc)) {
      mDesTv.setText(shortDesc);
    } else {
      mDesTv.setVisibility(View.GONE);
    }

    mDiscussionItemList = new ArrayList<PainPointDiscussionItem>();

    getDiscussionCommentList();

    this.mFooterView = LayoutInflater.from(this).inflate(
        R.layout.listview_placeholder, null);

  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

      if (lastSelect != mSelected) {
        Intent resultIntent = new Intent();
        setResult(RESULT_OK, resultIntent);

        finish();

        return true;
      }

    }
    return super.onKeyDown(keyCode, event);
  }

  private void getDiscussionCommentList() {

    new CustomAsyncTask(PainPointDiscussionActivity.this, new IAsyncTask() {

      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        // TODO Auto-generated method stub
        if (result.isSuccess()) {
          mPPDIW = JsonSerializer.getInstance().deserialize(result.data,
              PainPointDiscussionItemWrapper.class);

          if (mDiscussionItemList != null)
            mDiscussionItemList.clear();
          else
            mDiscussionItemList = new ArrayList<PainPointDiscussionItem>();

          mDiscussionItemList.addAll(mPPDIW.data);

          mPpdAdapter = null;

          mPpdAdapter = new PainPointDiscussionAdapter(activity,
              mDiscussionItemList);

          mPpdAdapter.setCommentDelegate(new CommentDelegate() {

            @Override
            public void likeDelegate(int id) {
              // TODO Auto-generated method stub
              like(id);
            }

            @Override
            public void publishCommentDelegate(int pid) {
              // TODO Auto-generated method stub
              // if (mHabitId != -1)
              // publishComment(comment, mHabitId, pid);
              mPID = pid;
              openCodeInputDialog();
            }

          });

          mDiscussionListView.setAdapter(mPpdAdapter);

          if (mDiscussionItemList.size() != 0)
            mDiscussionListView.addFooterView(mFooterView);

          mPpdAdapter.notifyDataSetChanged();

        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        // TODO Auto-generated method stub
        HashMap<String, Object> param_ = new HashMap<String, Object>();

        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);

        String url = HttpUtils.GET_COMMENTS_LIST_GET.replace("{id}",
            String.valueOf(mHabitId));

        return HttpUtils.startRequest(HttpUtils.API_URL + url, param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void publishComment(final String comment, final int habit_id,
      final int pid) {
    new CustomAsyncTask(PainPointDiscussionActivity.this, new IAsyncTask() {

      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        // TODO Auto-generated method stub
        getDiscussionCommentList();
        toastShow(result.data);
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        // TODO Auto-generated method stub
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        String url = HttpUtils.PUBLISH_COMMENTS_POST.replace("{id}",
            String.valueOf(habit_id));
        param_.put("comment", comment);
        param_.put("pid", pid);
        return HttpUtils.startRequest(HttpUtils.API_URL + url, param_,
            HttpUtils.TAG_POST_REQUEST);
      }
    }).execute();
  }

  private void like(final int id) {
    new CustomAsyncTask(PainPointDiscussionActivity.this, new IAsyncTask() {

      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        // TODO Auto-generated method stub
        toastShow(result.data);
        getDiscussionCommentList();
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        // TODO Auto-generated method stub
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put("id", id);
        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.LIKE_COMMENT_PUT, param_, HttpUtils.TAG_PUT_REQUEST);
      }
    }).execute();
  }

  @Override
  public void onResume() {
    super.onResume();
  }

  @Override
  public void onPause() {
    super.onPause();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
  }

  private void checkJoinState(boolean join) {
    if (join) {
      mJoinBtn.setBackgroundColor(Color.argb(255, 108, 230, 130));
      mJoinBtn.setText("已加入好习惯培养");
      if (!mSelectedList.contains(mHabitId)) {
        mSelectedList.add(mHabitId);
      }
    } else {
      mJoinBtn.setBackgroundColor(Color.argb(255, 106, 197, 253));
      mJoinBtn.setText("加入好习惯培养");
      if (mSelectedList.contains(mHabitId)) {
        int index = mSelectedList.indexOf(mHabitId);
        mSelectedList.remove(index);
      }
    }
    uploadPainPointList();
  }

  private void uploadPainPointList() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        String ids = convertList2String(mSelectedList);
        Log.e(TAG, ids);

        if (mGlobalLeUser != null) {
          param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        } else {
          LeUser lu = MyTeacherApp.getInstance().getUserTeacher();
          if (lu == null) {
            lu = Tools.restoreLeUser();
          }
          param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        }

        param_.put("habit_ids", ids);
        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.UPDATE_PAINPOINT_POST, param_,
            HttpUtils.TAG_POST_REQUEST);
      }
    }).execute();
  }

  private String convertList2String(ArrayList<Integer> ids) {
    String result = "";
    if (ids != null) {
      if (ids.size() == 0) {
        return "0";
      }
      int i = 0;
      int size = ids.size();
      for (; i < size; i++) {
        result += ids.get(i);
        if (i != size - 1) {
          result += ",";
        }
      }
    }
    return result;
  }

  /*
   * (non-Javadoc)
   *
   * @see android.view.View.OnClickListener#onClick(android.view.View)
   */
  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.edit_img:
      mPID = 0;
      openCodeInputDialog();
      break;
    case R.id.discussion_back_btn:
      break;
    case R.id.join_btn:
      mSelected = !mSelected;
      checkJoinState(mSelected);
      break;
    default:
      break;
    }
  }

  /**
   * 弹出输入框
   */
  @SuppressLint("InflateParams")
  private void setupDialog() {
    dialogHolder = new DialogHolder();

    Dialog mUserInputDialog = new Dialog(this, R.style.MyDialogStyleBottom);
    mUserInputDialog.setCancelable(true);
    mUserInputDialog.setCanceledOnTouchOutside(true);

    LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(
        R.layout.widget_input_comment, null);

    final EditText editext = (EditText) layout.findViewById(R.id.edit_code);
    final ImageView img = (ImageView) layout.findViewById(R.id.btn_action);
    img.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        final String comment = editext.getText().toString();
        if (Tools.isNotEmpty(comment)) {
          if (mHabitId != -1)
            publishComment(comment, mHabitId, mPID);
          closeInputMethod(editext.getWindowToken());
          if (dialogHolder != null && dialogHolder.dialog != null) {
            dialogHolder.dialog.dismiss();
          }
        } else {
          Toast
              .makeText(getApplicationContext(), "请输入评论内容", Toast.LENGTH_SHORT)
              .show();
        }
      }
    });
    editext.setOnEditorActionListener(new OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
          final String code = editext.getText().toString();

          if (Tools.isNotEmpty(code)) {
            // sendComment(idShare, code);
            closeInputMethod(editext.getWindowToken());
            if (dialogHolder != null && dialogHolder.dialog != null) {
              dialogHolder.dialog.dismiss();
            }
          } else {
            Toast.makeText(getApplicationContext(), "请输入评论内容",
                Toast.LENGTH_SHORT).show();
          }
          return true;
        }
        return false;
      }
    });

    LayoutParams param4 = new LayoutParams(-1, -1);
    param4.gravity = Gravity.BOTTOM;
    mUserInputDialog.addContentView(layout, param4);

    Window dialogWindow = mUserInputDialog.getWindow();
    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
    lp.width = -1;
    dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
    dialogWindow.setAttributes(lp);

    dialogHolder.dialog = mUserInputDialog;

    dialogHolder.dialog.setOnShowListener(new OnShowListener() {

      @Override
      public void onShow(DialogInterface dialog) {
        // TODO Auto-generated method stub
      }
    });

    dialogHolder.dialog.setOnDismissListener(new OnDismissListener() {

      @Override
      public void onDismiss(DialogInterface dialog) {

      }
    });

    dialogHolder.img = img;
    dialogHolder.editText = editext;
  }

  @SuppressLint("HandlerLeak")
  private final Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      if (msg.what == 0) {
        dialogHolder.editText.requestFocus();
        openInputMethod(dialogHolder.editText);
      } else {
        closeInputMethod(dialogHolder.editText.getWindowToken());
      }
    }
  };

  private void openCodeInputDialog(String code) {
    dialogHolder.editText.setText(code);

    dialogHolder.dialog.show();

    handler.sendEmptyMessageDelayed(0, 60);
  }

  private void openCodeInputDialog() {
    openCodeInputDialog("");
  }

}
